package net.newsmth.smthapp.android.ui;

import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;

import net.newsmth.smthapp.android.R;
import net.newsmth.smthapp.android.config.SmthNetStatusType;
import net.newsmth.smthapp.android.helper.AccountHelperImpl;
import net.newsmth.smthapp.android.model.Account;
import net.newsmth.smthapp.android.util.UIUtil;
import net.newsmth.smthapp.android.widget.ErrorView;

public class StartActivity extends BaseActivity {
    private AccountHelperImpl accountHelper;

    public void redirectToMainActivity() {
        UIUtil.redirectToFromActivity(this, MainActivity.class);
    }

    public void redirectToLoginActivity() {
        UIUtil.redirectToFromActivity(this, LoginActivity.class);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);

        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                initApplication();
            }
        }, 500);

        accountHelper = new AccountHelperImpl(this.appSettings, this.connection);

    }

    @Override
    protected ErrorView getGeneralErrorView() {
        return null;
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.start, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    //<editor-fold desc="Business Logic">
    public void initApplication() {
        Account account = accountHelper.loadAccount();

        if (accountHelper.login(account)) {
            connection.getSectionHot(0);
            redirectToMainActivity();
        } else {
            SmthNetStatusType netStatusType = connection.getErrorType();
            if (netStatusType == SmthNetStatusType.TOKEN_FAILURE) {
                redirectToLoginActivity();
            }
            if (netStatusType == SmthNetStatusType.NETWORK_FAILURE) {
                redirectToLoginActivity();
            }
        }
    }
    //</editor-fold>
}
